package com.demo.mvcframework.webmvc.servlet;

import com.demo.mvcframework.webmvc.annotation.MaginaAutoWired;
import com.demo.mvcframework.webmvc.annotation.MaginaController;
import com.demo.mvcframework.webmvc.annotation.MaginaRequestMapping;
import com.demo.mvcframework.webmvc.annotation.MaginaService;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.*;

/**
 * Created by cass on 2018/6/25.
 */
public class MaginaDispatcherServlet extends HttpServlet {

    private Properties contextConfig = new Properties();

    private List<String> classNames = new ArrayList<String>();

    private Map<String,Object> ioc = new HashMap<String,Object>();

    private  Map<String,Method> handlerMapping = new HashMap<String, Method>();
    @Override
    public void init(ServletConfig config) throws ServletException {
//        super.init(config);

        System.out.println("==========maginaSpring is init!!!===");

        //1.���������ļ�
        doLoadConfig(config.getInitParameter("contextConfigLocation"));

        //2.ɨ��������ص���
        doScanner(contextConfig.getProperty("scanPackage"));
        
        //3.��ʼ��ɨ�赽����
        doInstance();
        //4.ʵ������ע��
        doAutoWired();
        //5.��ʼ��HandlerMapping
        initHandlerMapping();
    }

    private void initHandlerMapping() {
        if(ioc.isEmpty()){
            return;
        }
        //��controller���д���
        for (Map.Entry<String,Object> entry : ioc.entrySet()){
            Class<?> clazz = entry.getValue().getClass();
            //
            if(clazz.isAnnotationPresent(MaginaController.class)){continue;}

            String baseUrl = "";
            if(clazz.isAnnotationPresent(MaginaRequestMapping.class)){
                MaginaRequestMapping requestMapping = clazz.getAnnotation(MaginaRequestMapping.class);
                baseUrl = requestMapping.value();
            }
            Method[] methods = clazz.getMethods();
            for(Method method : methods){
                if(method.isAnnotationPresent(MaginaRequestMapping.class)){
                    MaginaRequestMapping requestMapping = method.getAnnotation(MaginaRequestMapping.class);
                    String url = requestMapping.value();

                    url = baseUrl + url;
                    handlerMapping.put(url,method); 
                }
            }

            }
    }

    private void doAutoWired() {
        if(ioc.isEmpty()) {
            return;
        }
        for (Map.Entry<String,Object> entry:ioc.entrySet()){
            Field[] fields = entry.getValue().getClass().getDeclaredFields();
            //ǿ��ע��
            for (Field field :fields) {
                //����autoWired���ֶ�
                if (!field.isAnnotationPresent(MaginaAutoWired.class)) {
                    continue;
                }
                MaginaAutoWired autoWired = field.getAnnotation(MaginaAutoWired.class);
                String beanName = autoWired.value().trim();
                if("".equals(beanName)){
                    beanName = field.getType().getName();
                }
                //ǿ����Ȩ
                field.setAccessible(true);
                try {
                    field.set(entry.getValue(),ioc.get(beanName));
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }

            }
        }
    }

    private void doInstance()  {
        if(classNames.isEmpty()){return;}
//        Class.forName()
        try {
            for (String className : classNames){

                Class<?> clazz = Class.forName(className);
                //��ע�����ų�ʼ��
                if(clazz.isAnnotationPresent(MaginaController.class)){
                    Object obj = clazz.newInstance();
                    //��ʼ����Ҫ�ŵ�ioc����
                    //Ĭ������������ĸСд
                    String beanName = lowerFirstCase(clazz.getSimpleName());
                    ioc.put(beanName,obj);
                }else if(clazz.isAnnotationPresent(MaginaService.class)){
                    //1.Ĭ������ĸСд
                    //2.����ǽӿ�Ҫ������ʵ���ำֵ����
                    //3.����Զ���,�������Զ�������
                     MaginaService maginaService = clazz.getAnnotation(MaginaService.class);
                    String beanName = maginaService.value();
                    if("".equals(beanName.trim())){
                        beanName = lowerFirstCase(clazz.getSimpleName());
                    }
                    Object instance = clazz.newInstance();
                    ioc.put(beanName,instance);
                    //����������ø��������   
                    Class<?>[] interfaces = clazz.getInterfaces();
                    for (Class<?> c : interfaces){
                        ioc.put(c.getName(),instance);
                    }
                }else{
                    //����,�ͼ���
                    continue;
                }
              }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    private void doScanner(String scanPackage) {
        //URL url =this.getClass().getClassLoader().getResource("/" + scanPackage.replace("\\.", "/"));
        URL url=this.getClass().getClassLoader().getResource("/"+scanPackage.replaceAll("\\.","/"));//将所有.转义获取对应的路径
        File classDir = new File(url.getFile());
        for(File file : classDir.listFiles()){
            if(file.isDirectory()){
                doScanner(scanPackage + "." + file.getName());
            }else{
                String className = (scanPackage + "." + file.getName().replace(".classs",""));
                classNames.add(className );
            }
        }

    }

    private void doLoadConfig(String contextConfigLocation) {
        InputStream is = this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation);
        try {
            contextConfig.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(null != is){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        super.doPost(req, resp);
        //6.�ȴ�����
        try {
            doDispatch(req,resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws Exception{
        String url = req.getRequestURI();
        String contextPath = req.getContextPath();
        url  = url .replace(contextPath,"").replaceAll("/+","/");

        if(handlerMapping.containsKey(url)){
            resp.getWriter().write("404 Not Found!!!");
        }
        Method method = handlerMapping.get(url);
        System.out.println(method);
    }

    private String lowerFirstCase(String str){
        char[] chars = str.toCharArray();
        chars[0] += 32;
        return String.valueOf(chars);
    }
}
